<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全选</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        width: 200px;
        margin: 20px auto 0;
        padding: 10px;
        box-sizing: border-box;
        text-align: center;
        align-items: center;
        border: 1px solid pink;
    }

    hr {
        margin: 10px 20px;
    }

    .select {
        margin-top: 10px;
    }

    form {
        user-select: none;
    }
</style>
<body>
<form class="box">
    <label><input class="all-select" type="checkbox"></label><span> 全选</span><br>
    <hr><!--<hr> 标签在 HTML 页面中创建一条水平线-->
    <label><input class="select" type="checkbox"></label><span> 选项一</span><br>
    <label><input class="select" type="checkbox"></label><span> 选项二</span><br>
    <label><input class="select" type="checkbox"></label><span> 选项三</span><br>
    <label><input class="select" type="checkbox"></label><span> 选项四</span><br>
</form>

<script>
    //1.获取元素
    var allSelect = document.querySelector('.all-select')
    var select = document.querySelectorAll('.select')

    //2.获取全选状态
    allSelect.onclick = function () {
        var allState = allSelect.checked
        //2-1.将全选状态赋给每个选项
        for (var i = 0; i < select.length; i++) {
            select[i].checked = allState
        }
    }

    //3.循环每个选项绑定点击事件
    for (var i = 0; i < select.length; i++) {
        select[i].onclick = function () {
            //3-1假设所有选项都是被选中的
            var State = true

            //3-2循环获取所有选项的状态，判断是否全部选项都选上
            for (var j = 0; j < select.length; j++) {
                //一旦有一个选项没被选中就推翻假设
                if (select[j].checked === false) {
                    State = false
                    break
                }
            }
            //最后赋State的值给全选选项
            allSelect.checked = State
        }
    }

</script>
</body>
</html>